require('../css/player.less')
window.utils.namichref()
let userID = location.search.split('=')[1]
if(!userID){
    location.href = './CourseTraining.html'
}
let videos = document.querySelector('#video')
let vidtitle = document.querySelector('#vidtitle')
let current = document.querySelector('#current')
let Totallength = document.querySelector('#Totallength')
let previous = document.querySelector('#previous')
let stop = document.querySelector('#stop')
let next = document.querySelector('#next')
let Mask = document.querySelector('#Mask')
let progres = document.querySelector('.progress')
let play = document.querySelector('#play')
let end = document.querySelector('#end')
let index = 0
window.$http.get(`/sports/courseDetail?id=${userID}`, function (res) {
	if (res.status === 0) {
		Totallength.innerHTML = res.data.fragments.length
		// 播放
		function playerplay() {
			videos.src = window.$BASE_URL + res.data.fragments[index].videoUrl
			vidtitle.innerHTML = res.data.fragments[index].title
			current.innerHTML = index + 1
			window.setTimeout(function () {
				videos.play()
			}, 30)
		}
		playerplay()
		// 播放下一个
		function playernext() {
			if (index + 1 === res.data.fragments.length) return
			index += 1
			playerplay()
		}
		//视频结束播放下一个
		videos.addEventListener('ended', playernext)
		// 播放上一个
		previous.addEventListener('click', function () {
			if (index === 0) return
			index -= 1
			playerplay()
		})
		// 播放下一个
		next.addEventListener('click', playernext)
		let setr=[]
		//进度条
		let tiem
		function progressbar() {
			tiem = window.setInterval(function () {
				setr[index] = video.currentTime
				progres.style.width = `${
					(video.currentTime * 100) / video.duration
				}%`
			}, 20)
		}
		progressbar()
		//停止
		stop.addEventListener('click', function () {
			videos.pause()
			window.clearInterval(tiem)
			Mask.style.display = 'flex'
		})
        // 继续播放
        play.addEventListener('click',function(){
            Mask.style.display = 'none'
            videos.play()
            progressbar()
        })
        //结束播放
        end.addEventListener('click',function(){
            let endtime=0
            setr.forEach(function(item){
                endtime+=item
            })
            let params = {
				calorie: endtime * 1.3,
				id: userID,
				takeTime: endtime,
				userId: JSON.parse(localStorage.getItem('users')).userId,
			}
            window.$http.post('/sports/saveTrain',params,function(res){
                console.log(res);
                if(res.status===0){
                    window.location.href = '.CourseTraining.html'
                }
            })
        })
	}
})
